using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

public class NumList
{
    public int a { get; set; }
    public float b { get; set; }
}

public class FuzzTest
{
    // 待测函数
    public static int Div(NumList list)
    {
        if (list.b == 0.0f)
        {
            throw new DivideByZeroException();
        }
        float result = list.a / list.b;
        if (float.IsInfinity(result))
        {
            throw new OverflowException("Result is too large");
        }
        if (float.IsNaN(result))
        {
            throw new ArithmeticException("Invalid operation resulted in NaN");
        }
        return (int)result;
    }

    // 变异规则1：整数位翻转变异
    public static int BitFlipMutation(int originalInput)
    {
        Random rand = new Random();
        return originalInput ^ (1 << rand.Next(0, 32));
    }

    // 变异规则2：浮点位翻转变异
    public static float FloatBitFlipMutation(float originalInput)
    {
        Random rand = new Random();
        int intBits = BitConverter.ToInt32(BitConverter.GetBytes(originalInput), 0);
        intBits ^= (1 << rand.Next(0, 32));
        return BitConverter.ToSingle(BitConverter.GetBytes(intBits), 0);
    }

    // 变异规则3：边界值变异
    public static int BoundaryMutation(int originalInput)
    {
        int[] boundaries = { int.MinValue, int.MaxValue, 0, -1, 1 };
        Random rand = new Random();
        return rand.Next(0, 2) == 0 ? originalInput : boundaries[rand.Next(0, boundaries.Length)];
    }

    // 变异规则4：浮点边界值变异
    public static float FloatBoundaryMutation(float originalInput)
    {
        float[] boundaries = { float.MinValue, float.MaxValue, 0.0f, -1.0f, 1.0f, float.Epsilon, float.NaN, float.PositiveInfinity, float.NegativeInfinity };
        Random rand = new Random();
        return rand.Next(0, 2) == 0 ? originalInput : boundaries[rand.Next(0, boundaries.Length)];
    }

    // 变异规则5：随机值变异
    public static int RandomValueMutation(int originalInput)
    {
        Random rand = new Random();
        return rand.Next(int.MinValue, int.MaxValue);
    }

    // 变异规则6：浮点随机值变异
    public static float FloatRandomValueMutation(float originalInput)
    {
        Random rand = new Random();
        return (float)(rand.NextDouble() * (float.MaxValue - float.MinValue) + float.MinValue);
    }

    // 变异规则7：算术变异
    public static int ArithmeticMutation(int originalInput)
    {
        Random rand = new Random();
        int[] operations = { originalInput + 1, originalInput - 1, originalInput * 2, originalInput / 2 };
        return operations[rand.Next(0, operations.Length)];
    }

    // 变异规则8：浮点算术变异
    public static float FloatArithmeticMutation(float originalInput)
    {
        Random rand = new Random();
        float[] operations = { originalInput + 1.0f, originalInput - 1.0f, originalInput * 2.0f, originalInput / 2.0f };
        return operations[rand.Next(0, operations.Length)];
    }

    // 执行所有变异并保存结果
    public static void TestAndSaveResults(string filePath)
    {
        var existingEntries = File.ReadAllLines(filePath)
                                .Where(line => !string.IsNullOrWhiteSpace(line))
                                .ToList();

        using (StreamWriter writer = new StreamWriter(filePath, append: true))
        {
            foreach (var line in existingEntries)
            {
                var parts = line.Split(',');
                if (parts.Length < 2)
                    continue;

                int a = int.Parse(parts[0]);
                float b = float.Parse(parts[1]);

                var mutatedA = new List<int>
                {
                    BitFlipMutation(a),
                    BoundaryMutation(a),
                    RandomValueMutation(a),
                    ArithmeticMutation(a)
                };

                var mutatedB = new List<float>
                {
                    FloatBitFlipMutation(b),
                    FloatBoundaryMutation(b),
                    FloatRandomValueMutation(b),
                    FloatArithmeticMutation(b)
                };

                writer.WriteLine($"{a},{b}");

                foreach (var ma in mutatedA)
                {
                    foreach (var mb in mutatedB)
                    {
                        writer.WriteLine($"{ma},{mb}");
                    }
                }
            }
        }
    }

    public static void Main(string[] args)
    {
        string filePath = "div_test_results.txt";

        if (!File.Exists(filePath))
        {
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine("10,2");
                writer.WriteLine("0,1");
                writer.WriteLine("1,0");
                writer.WriteLine("-10,2");
                writer.WriteLine("10,-2");
                writer.WriteLine("1000000,1000");
            }
        }

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine($"Iteration {i + 1}: Processing data...");
            TestAndSaveResults(filePath);

            var entries = File.ReadAllLines(filePath)
                            .Where(line => !string.IsNullOrWhiteSpace(line))
                            .ToList();

            foreach (var line in entries)
            {
                var parts = line.Split(',');
                if (parts.Length < 2)
                    continue;

                int a = int.Parse(parts[0]);
                float b = float.Parse(parts[1]);

                try
                {
                    var numList = new NumList { a = a, b = b };
                    int result = Div(numList);
                    Console.WriteLine($"Div({a}, {b}) = {result}");
                }
                catch (DivideByZeroException)
                {
                    Console.WriteLine($"Div({a}, {b}): DivideByZeroException");
                }
                catch (OverflowException ex)
                {
                    Console.WriteLine($"Div({a}, {b}): {ex.Message}");
                }
                catch (ArithmeticException ex)
                {
                    Console.WriteLine($"Div({a}, {b}): {ex.Message}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Div({a}, {b}): Unexpected exception - {ex.GetType().Name}: {ex.Message}");
                }
            }
        }

        Console.WriteLine("All iterations completed. Results saved to " + filePath);
    }
}